package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.util.Random;

import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonFunction;
import org.json.JSONObject;
/**
 * 发送邮箱验证码通过Ajax方法调用URL：ajax_send_mail_vcode<br>
 * 必须登陆：false<br>
 * 必须管理：false<br>
 * 参数：<br>
 * mail，必须，发送验证码的邮箱<br>
 * 注：无<br>
 * @author fc
 */
public class AjaxSendMailVerificationCode extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final StringBuffer buffer = new StringBuffer("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
	private static final char[] strchar = new char[4];
	private static final Random random = new Random();
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			for(int i=0;i<4;++i){
				strchar[i] = buffer.charAt(random.nextInt(36));
			}
			CommonFunction.send_mail(req.getParameter("mail"), "H5Fun邮箱验证码", String.format("您的邮箱验证码是：%s",String.valueOf(strchar)));
			req.getSession().setAttribute("mail_vcode", String.valueOf(strchar));
			json.put("type", 0);
			json.put("msg", "邮件发送成功");
		} catch (AddressException e) {
			json.put("type", -1);
			json.put("msg", "邮箱地址错误");
		} catch (Exception e) {
			json.put("type", -2);
			json.put("msg", "未知错误");
			Logger.getRootLogger().error(e);
		}
		resp.getWriter().print(json);
	}
}
